<template>
  <div class="flight-tab-content">
    <div class="parameters-selection">
      <div class="parameter-row">
        <div class="parameter-item" v-for="(item, key) in parameterItems" :key="key">
          <el-checkbox v-model="parameters[key]" @change="updateChartOptions">{{ item.name }}</el-checkbox>
        </div>
      </div>
    </div>

    <div class="chart-container">
      <div ref="chartRef" class="echarts-chart"></div>
    </div>

    <div class="data-summary">
      <div class="summary-item" v-for="(item, key) in summaryItems" :key="key">
        <div class="item-title">{{ item.title }}</div>
        <div class="item-value">{{ infoData.flightInfo[key] || '--' }} {{ item.unit }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, onMounted, onUnmounted, watch, nextTick,computed } from 'vue';
import * as echarts from 'echarts/core';
import { LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import useInfoDataStore from "@/stores/modules/infoData";
import moment from 'moment';


const infoData = useInfoDataStore();

// 注册必要的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DataZoomComponent,
  LegendComponent,
  LineChart,
  CanvasRenderer
]);

const props = defineProps({

  active: {
    type: Boolean,
    default: false
  }
});

// 图表元素引用
const chartRef = ref(null);

// 图表实例
let chart = null;

// 选择的参数
const parameters = ref({
  altitude: true,
  temperature: true,
  humidity: true,
  speed: true,
  direction: true
});

// 参数项配置
const parameterItems = {
  altitude: { name: '高度', color: '#36a2eb', unit: '米' },
  temperature: { name: '温度', color: '#ff9f40', unit: '°C' },
  humidity: { name: '相对湿度', color: '#4bc0c0', unit: '%' },
  speed: { name: '航速', color: '#ff6384', unit: 'km/h' },
  direction: { name: '航向', color: '#0066ff', unit: '°' }
};

// 摘要项配置
const summaryItems = {
  altitude: { title: '当前高度', unit: '米' },
  temperature: { title: '当前温度', unit: '°C' },
  humidity: { title: '相对湿度', unit: '%' },
  airPressure: { title: '气压', unit: 'hPa' }
};

// 历史数据
const historyData = computed(() => infoData.paramData);

// 数据范围
const dataRanges = ref({
  altitude: { min: 0, max: null },
  temperature: { min: 0, max: null },
  humidity: { min: 0, max: 100 },
  speed: { min: 0, max: null },
  direction: { min: 0, max: 360 }
});

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return;

  if (chart) {
    chart.dispose();
    chart = null;
  }

  try {
    // 创建新的图表实例
    chart = echarts.init(chartRef.value);


    const baseOption = {
      animation: false,
      animationDuration: 0,
      animationDurationUpdate: 0,
      animationEasing: 'linear',
      animationEasingUpdate: 'linear'
    };

    chart.setOption(baseOption);
    // updateChartOptions();

    window.addEventListener('resize', handleResize);
  } catch (error) {
    console.error('初始化图表失败:', error);
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize();
  }
};

// 更新图表配置
const updateChartOptions = () => {
  if (!chart) return;

  try {
    // 获取时间数据
    const timeData = historyData.value.length > 0
      ? historyData.value.map(item => moment(Number(item.timeStamp)).format('HH:mm:ss'))
      : ['--'];

    const metrics = Object.entries(parameters.value)
      .filter(([_, enabled]) => enabled)
      .map(([metric]) => metric);

    if (metrics.length === 0) {
      const emptyOption = {
        animation: false,
        backgroundColor: '#fff',
        title: {
          text: '请至少选择一个参数',
          textStyle: {
            color: '#999',
            fontSize: 14,
            fontWeight: 'normal'
          },
          left: 'center',
          top: 'center'
        },
        grid: {
          left: '8%',
          right: '10%',
          bottom: '0%',
          top: '70px',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['--'],
          axisLine: {
            lineStyle: {
              color: '#999',
              width: 1
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: true,
            lineStyle: {
              color: '#999',
              width: 1
            }
          }
        },
        series: []
      };
      chart.setOption(emptyOption, true);
      return;
    }

    // const zoomConfig = historyData.value.length > 50
    //   ? { start: Math.max(0, (1 - 50 / historyData.value.length) * 100), end: 100 }
    //   : { start: 0, end: 100 };

    const yAxis = metrics.map((metric, index) => getYAxisConfig(metric, index, metrics.length));
    const series = metrics.map((metric, index) => getSeriesConfig(metric, index));

    // 如果没有数据，显示空状态
    if (historyData.value.length === 0) {
      const emptyOption = {
        animation: false,
        title: {
          text: '暂无数据',
          textStyle: {
            color: '#999',
            fontSize: 14,
            fontWeight: 'normal'
          },
          left: 'center',
          top: 'center'
        },
        yAxis: yAxis,
        series: series
      };
      chart.setOption(emptyOption);
      return;
    }

    const option = {
      animation: false,
      animationDuration: 0,
      animationDurationUpdate: 0,
      backgroundColor: '#fff',
      color: ['#36a2eb', '#ff9f40', '#4bc0c0', '#ff6384', '#0066ff'],
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
          animation: false,
          label: {
            backgroundColor: '#6a7985'
          }
        },
        backgroundColor: 'rgba(255, 255, 255, 0.95)',
        borderColor: '#eee',
        borderWidth: 1,
        padding: 10,
        textStyle: {
          color: '#333'
        },
        extraCssText: 'box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);'
      },
      legend: {
        data: series.map(s => s.name),
        top: 10,
        textStyle: {
          color: '#666',
          fontSize: 12
        },
        selectedMode: false,
        itemWidth: 15,
        itemHeight: 10,
        itemGap: 12,
        icon: 'roundRect'
      },
      grid: {
        left: '8%',
        right: '10%',
        bottom: '7%',
        top: '70px',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: timeData,
        axisLine: {
          lineStyle: {
            color: '#999',
            width: 1
          }
        },
        axisLabel: {
          color: '#666',
          fontSize: 11,
          formatter: value => value
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: yAxis,
      series: series,
      dataZoom: {
        realtime: true,
        start: 0,
        end: 100,
        bottom: 10,
        height: 25,
        fillerColor: 'rgba(64, 158, 255, 0.15)',
        textStyle: {
          color: '#666'
        },
      }
    };
    chart.setOption(option, true);
  } catch (error) {
    console.error('更新图表配置失败:', error);
    setTimeout(() => {
      initChart();
    }, 100);
  }
};

// 获取Y轴配置
const getYAxisConfig = (metric, index, totalAxes) => {
  const configs = {
    altitude: {
      name: '高度(m)',
      color: '#36a2eb',
      formatter: '{value}'
    },
    temperature: {
      name: '温度(°C)',
      color: '#ff9f40',
      formatter: '{value}'
    },
    humidity: {
      name: '湿度(%)',
      color: '#4bc0c0',
      formatter: '{value}'
    },
    speed: {
      name: '航速(km/h)',
      color: '#ff6384',
      formatter: '{value}'
    },
    direction: {
      name: '航向(°)',
      color: '#0066ff',
      formatter: '{value}'
    }
  };

  const config = configs[metric];

  const positions = {
    altitude: { position: 'left', offset: 0 },
    temperature: { position: 'right', offset: 0 },
    humidity: { position: 'left', offset: 50 },
    speed: { position: 'right', offset: 50 },
    direction: { position: 'right', offset: 100 }
  };

  const { position, offset } = positions[metric];

  return {
    name: config.name,
    nameTextStyle: {
      color: config.color,
      padding: [0, 0, 0, position === 'left' ? 0 : 10],
      fontSize: 12,
      fontWeight: 500
    },
    type: 'value',
    position,
    offset,
    min: dataRanges.value[metric].min,
    max: dataRanges.value[metric].max,
    axisLine: {
      show: true,
      lineStyle: {
        color: config.color,
        width: 1.5
      }
    },
    axisLabel: {
      formatter: config.formatter,
      color: config.color,
      fontSize: 11,
      margin: 3
    },
    splitLine: {
      show: index === 0,
      lineStyle: {
        color: '#eee',
        type: 'dashed'
      }
    }
  };
};

// 获取系列配置
const getSeriesConfig = (metric, yAxisIndex) => {
  const configs = {
    altitude: {
      name: '高度',
      color: '#36a2eb'
    },
    temperature: {
      name: '温度',
      color: '#ff9f40'
    },
    humidity: {
      name: '湿度',
      color: '#4bc0c0'
    },
    speed: {
      name: '航速',
      color: '#ff6384'
    },
    direction: {
      name: '航向',
      color: '#0066ff'
    }
  };

  const config = configs[metric];

  return {
    name: config.name,
    type: 'line',
    yAxisIndex: yAxisIndex,
    data: historyData.value.map(item => item[metric]),
    smooth: true,
    symbol: 'none',
    showSymbol: false,
    lineStyle: {
      width: 2,
      color: config.color
    },
    emphasis: {
      focus: 'series',
      lineStyle: {
        width: 3
      }
    },
    animation: false
  };
};

// 更新飞行数据
const updateFlightData = (payload) => {
  if (!payload) return;

  historyData.value = payload;
  // 添加到历史数据
  // if (payload.temperature || payload.humidity || payload.altitude) {
  //   const lastData = historyData.value[historyData.value.length - 1];
  //   const hasChanged = !lastData ||
  //     ['temperature', 'humidity', 'altitude', 'speed', 'direction'].some(key =>
  //       lastData[key] !== payload[key]);

  //   if (hasChanged) {
  //     const newData = {
  //       ...payload,
  //       // 确保updateTime字段存在，用于图表显示
  //       updateTime: payload.updateTime || payload.timestamp || new Date().toLocaleTimeString('zh-CN', { hour12: false })
  //     };

  //     historyData.value.push(newData);

  //     if (historyData.value.length > 500) {
  //       historyData.value = historyData.value.slice(-500);
  //     }

  //     // 更新图表
  //     
  //   }
  // }
};

// // 刷新飞行数据
// const refreshFlightData = (value) => {
//   const now = new Date();
//   const newData = {
//     altitude: Math.floor(Math.random() * 2000) + 5000,
//     temperature: Math.floor(Math.random() * 20) + 10,
//     humidity: Math.floor(Math.random() * 60) + 20,
//     airPressure: Math.floor(Math.random() * 200) + 900,
//     windSpeed: Math.floor(Math.random() * 20),
//     windDirection: Math.floor(Math.random() * 360),
//     speed: Math.floor(Math.random() * 100) + 200,
//     direction: Math.floor(Math.random() * 360),
//     updateTime: now.toLocaleTimeString('zh-CN', { hour12: false })
//   };
// console.log('newData', value);
//   // 添加到历史数据
//   historyData.value.push(value);

//   // 限制历史数据大小
//   if (historyData.value.length > 50) {
//     historyData.value = historyData.value.slice(-50);
//   }

//   // 更新图表
//   updateChartOptions();
// };

// 组件挂载时初始化
onMounted(() => {
  nextTick(() => {
    if (chartRef.value) {
      initChart();
    }
  });
});

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize);

  if (chart) {
    chart.dispose();
    chart = null;
  }
});

// 监听数据变化
watch(() => infoData.paramData, (newVal) => {
  if (newVal && props.active) {
    nextTick(() => {
      updateChartOptions();
    });
  }
}, { deep: true });

// 监听参数变化，更新图表
watch(() => parameters.value, () => {
  nextTick(() => {
    updateChartOptions();
  });
}, { deep: true });

// 监听活动状态变化
watch(() => props.active, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initChart();
    });
  }
});

// defineExpose({
//   refreshFlightData
// });
</script>

<style lang="scss" scoped>
.flight-tab-content {
  display: flex;
  flex-direction: column;
  flex: 1;
  overflow: hidden;

  .parameters-selection {
    padding: 10px 15px;
    background-color: #fff;
    border-bottom: 1px solid #eee;

    .parameter-row {
      display: flex;
      flex-wrap: wrap;
      gap: 15px;

      .parameter-item {
        font-size: 13px;
      }
    }
  }

  .chart-container {
    flex: 1;
    padding: 10px;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    border-radius: 4px;
    box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.03);

    .echarts-chart {
      width: 100%;
      height: 100%;
    }
  }

  .data-summary {
    padding: 10px 15px;
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    background-color: #f9f9f9;
    border-top: 1px solid #eee;

    .summary-item {
      background-color: #fff;
      border-radius: 6px;
      padding: 12px;
      min-width: 100px;
      flex: 1;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      transition: all 0.2s ease;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      }

      .item-title {
        font-size: 12px;
        color: #666;
        margin-bottom: 6px;
      }

      .item-value {
        font-size: 16px;
        color: #333;
        font-weight: 500;
      }
    }
  }
}
</style>